<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="data-preview__main" v-loading="loading">
    <el-button style="margin-bottom: 10px" size="small" @click="goBack">返回上一级</el-button>
    <el-button v-if="props.pageType == 'EDIT'" style="margin-bottom: 10px" type="primary" size="small" @click="saveMaterialData">保存数据</el-button>
    <div class="data-preview__content">
      <el-card shadow="never" :class="['treeDiv', 'card-shadow', props.type]" v-loading="loading">
        <!-- <el-table-column  label="ID" align="center" prop="_id" width="260" show-overflow-tooltip /> -->
        <!-- {{ props.currentChooseId }} -->
        <el-tree
          ref="materialTree"
          :data="treeData"
          node-key="index"
          highlight-current
          :props="defaultProps"
          default-expand-all
          :current-node-key="currentChooseId"
          :expand-on-click-node="false"
          icon-class="el-icon-arrow-right"
          @node-click="treeSelect"
        >
          <template #default="{ data }">
            <span style="display: flex; align-items: center">
              <span class="sub_title"> {{ data.data }}</span>
            </span>
          </template>
        </el-tree>
        <!-- 自定义右键菜单 -->
        <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
          <ul>
            <li @click="handleMenuClick('delete')">
              <el-button size="small" link type="primary" icon="Delete">删除</el-button>
            </li>
          </ul>
        </div>
      </el-card>
      <el-card shadow="never" :class="['right', 'card-shadow', props.type]" style="overflow: auto">
        <!-- <el-form ref="formRef" :model="nodeForm" :rules="rules" label-width="150px" size="small">
          <el-form-item v-for="(item, index) in columns" :key="index" :label="item.chinese" :prop="item.field">
            <el-input v-model.trim="nodeForm[item.field]" placeholder="请输入" clearable />
          </el-form-item>
        </el-form> -->
        <el-descriptions :column="1" border style="width: 100%" class="adaptive-column">
          <el-descriptions-item
            v-for="(des, index) in columns"
            :key="index"
            width="150px"
            :label="des.chinese"
            label-align="right"
            align="center"
            label-class-name="my-label"
            class-name="my-content"
          > 
            <!-- <el-image v-if="des.type == 'image'" :src="fileAbsolutePath() + des.data" fit="fit" /> -->
            <template v-if="des.type == 'image'">
              <el-link v-if="des.data" style="color: #409EFF;" size="small" type="primary" :href="des.data" target="_blank">
                查看图片 
              </el-link>
              <span v-else>暂无数据</span>
            </template>
            <div class="ellipsis-text" v-else>
              <el-input v-if="props.pageType == 'EDIT'" v-model="des.data"></el-input>
              <span v-else>{{ des.data }}</span>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <el-tabs v-if="!justShowForm" v-model="activeName" @tab-click="handleClick" style="width: 100%">
          <el-tab-pane v-for="(tab, index) in fields" :label="tab.chinese" :name="index" :key="index">
            <el-descriptions v-if="tab.type == 'object'" :column="1" border style="width: 100%" class="adaptive-column">
              <el-descriptions-item
                v-for="(des, i) in tab.data"
                :key="i"
                width="150px"
                :label="des.chinese + '(' + des.field + ')'"
                label-align="right"
                align="center"
                label-class-name="my-label"
                class-name="my-content"
              >
               <!-- <el-image v-if="des.type == 'image'" :src="fileAbsolutePath() + des.data" fit="fit" /> -->
               <template v-if="des.type == 'image'">
                  <el-link v-if="des.data" size="small" style="color: #409EFF;" type="primary" :href="des.data" target="_blank">
                    查看图片 
                  </el-link>
                  <span v-else>暂无数据</span>
                </template>
                <template v-else>
                  <template v-if="des.type == 'object'">
                    <el-descriptions :column="1" border style="width: 100%;" class="adaptive-column">
                      <el-descriptions-item
                        v-for="(des1, i1) in des.data"
                        :key="i1"
                        :label="des1.chinese + '(' + des1.field + ')'"
                        label-align="right"
                        align="center"
                        width="150px"
                        label-class-name="my-label"
                        class-name="my-content"
                        >
                        <template v-if="des1.type == 'image'">
                          <el-link v-if="des1.data" size="small" style="color: #409EFF;" type="primary" :href="des1.data" target="_blank">
                            查看图片 
                          </el-link>
                          <span v-else>暂无数据</span>
                        </template>
                        <template v-else>
                          <template v-if="des1.type == 'object'">
                            
                          </template>
                          <template v-else-if="des1.type == 'basic'">
                            {{ des1.data }}
                          </template>
                        </template>    
                      </el-descriptions-item>
                    </el-descriptions>
                  </template>
                  <template v-else-if="des.type == 'basic'">
                    {{ des.data }}
                  </template>
                  <template v-else-if="des.type == 'table'">
                    <el-table :data="des.data" border>
                      <el-table-column v-for="(td,index) in filterTableColumns(des.data[0])" :key="td._index" :label="td.chinese + '(' + td.field + ')'" :prop="td.field" min-width="120">
                        <template #default="scope">
                          <span>{{ scope.row[td._index]['data'] || '' }}</span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                </template>
              </el-descriptions-item>
            </el-descriptions>
            <el-table v-else :data="tab.data" border>
              <el-table-column v-for="(td,index) in filterTableColumns(tab.data[0])" :key="td._index" :label="td.chinese + '(' + td.field + ')'" :prop="td.field" min-width="150">
                <template #default="scope">
                  <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="scope.row[td._index]['data']"></el-input>
                  <span v-else>{{ scope.row[td._index]['data'] || '' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup name="MaterialDataPreview">
import { mockData } from './test.js';
import { dataServicesDataList, dataServicesHistoryDataList } from '@/api/dataServices/index.ts';
import { getMaterialTreeNew, getMaterialNodeInfo, updateMaterialNodeData, deleteMaterialNodeData } from '@/api/material/index.ts';
const emit = defineEmits(['handleEvent']);
const props = defineProps(['param', 'row', 'rowData', 'fieldList', 'height', 'tableName', 'currentChooseId', 'pageType', 'type']);
const loading = ref(false);
const nodeForm = ref({});
const columns = ref([]);
const fields = ref([]);
const currentChooseId = ref(null);
const treeData = ref([]);
const activeName = ref(0);
const rules = {};
const nodeData = ref({});
const nodeContent = ref(null);
const menuVisible = ref(false);
const wrapper = ref(null);
const justShowForm = ref(true);
const menuStyle = ref({
  left: 0,
  top: 0
});
const defaultProps = {
  children: 'children',
  label: 'chinese'
};
const fileAbsolutePath = () => {
  let origin = window.location.origin;
  if (origin == 'http://localhost' || origin == 'http://172.16.41.118') {
    return "http://172.16.41.118/file" 
  } else {
    return origin+"/isfd/file"
  }
  
}

const filterTableColumns = (cols) => {
  cols.forEach((item, index) => {
    item._index = index;
  })
  return cols.filter(col => col.type !== 'info');
}

// 右键点击
const openMenu = (event, data, node, element) => {
  if (!data.children || data.children.length === 0) {
    // menuLevel.value = node.level;
    nodeContent.value = data;
    // 显示菜单
    menuVisible.value = true;
    // 阻止默认的右键菜单显示
    event.preventDefault();
    // 设置菜单的位置
    menuStyle.value.left = 200 + 'px';
    console.log('');
    menuStyle.value.top = event.clientY - 162 + 'px';
  }
};
const handleClick = (event) => {
  // 检查点击是否发生在外部
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};
const handleMenuClick = () => {
  if (nodeContent.value?.detail?.objectId == nodeData.value?.detail?.objectId) {
    fields.value = [];
    columns.value = [];
  }
  deleteMaterialNodeData({ tableName: nodeContent.value?.detail?.tableName, objectId: nodeContent.value?.detail?.objectId }).then((res) => {
    if (res.code == 200) {
      ElMessage({ showClose: true, message: '材料信息删除成功', type: 'success' });
      getTreeData(props.tableName);
    }
  });
};
const goBack = () => {
  emit('handleEvent', { component: 'Index', currentChooseId: props.currentChooseId, param: props.param });
};
// tree选择事件
const treeSelect = (selected) => {
  // currentChooseId.value = selected.id;
  if (!selected.children || selected.children.length == 0) {
    justShowForm.value = false;
  } else {
    justShowForm.value = true;
  }
  // if (!selected.children || selected.children.length == 0) {
  nodeData.value = selected;
  getTreeInfo(selected?.detail?.tableName, selected?.detail?.objectId, 1);
  // }
};

// 保存节点数据
const saveMaterialData = () => {
  let params = {
    tableName: nodeData.value?.detail?.tableName,
    objectId: nodeData.value?.detail?.objectId,
    data: [...fields.value, ...columns.value]
  };
  updateMaterialNodeData(params).then((res) => {
    res.code == 200 && ElMessage({ showClose: true, message: '材料信息保存成功', type: 'success' });
  });
};

const getTreeData = (params) => {
  loading.value = true;
  getMaterialTreeNew(params)
    .then((res) => {
      treeData.value = res.data;
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};
const getTreeInfo = (tableName, objectId, mergeMode) => {
  getMaterialNodeInfo({
    tableName,
    objectId,
    mergeMode
  }).then((res) => {
    fields.value = [];
    columns.value = [];
    fields.value = res.data.filter((item) => {
      return ['table', 'object'].includes(item.type);
    });
    columns.value = res.data.filter((item) => {
      return !['table', 'object'].includes(item.type);
    });
  });
};

onMounted(() => {
  if (props.param == 'dataService' && props.rowData.modelId) {
    if (props.rowData) {
      loading.value = true;
      dataServicesDataList(props.rowData)
        .then((res) => {
          treeData.value = res.data;
          loading.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } else if (props.param == 'dataService' && !props.rowData.modelId) {
    loading.value = true;
    if (props.rowData) {
      dataServicesHistoryDataList(props.rowData)
        .then((res) => {
          treeData.value = res.data.record;
          loading.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } else {
    props.param == 'searchByObjectId'
      ? getTreeData({ objectIds: [props.row._id], tableName: props.tableName })
      : getTreeData({ tableName: props.tableName });
  }

  window.addEventListener('click', handleClick);
});
onUnmounted(() => {
  window.removeEventListener('click', handleClick);
});
</script>

<style lang="scss" scoped>
.data-preview__main {
  padding: 20px;
  overflow-y: auto;
  width: 100%;
  // height: calc(100vh - 148px);
  .custom-menu {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ebebeb;
    border-radius: 3px;
    width: 80px;
    z-index: 1000;
    font-size: 12px;
    ul {
      margin: 0;
      padding: 5px 0;
      list-style: none;
      font-size: 12px;
    }
    ul li {
      padding: 3px 15px;
      cursor: pointer;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    ul li:hover {
      background-color: #eee;
    }
  }
  .data-preview__content {
    display: flex;
    position: relative;
    .card-shadow {
      box-shadow:
        0 2px 4px rgba(0, 0, 0, 0.1),
        /* 主阴影 */ 0 8px 16px rgba(0, 0, 0, 0.05); /* 环境光 */
      transition: box-shadow 0.3s ease;
    }
    .treeDiv {
      flex: 0 0 300px;
      margin-right: 20px;
      max-height: calc(100vh - 158px); // 227
      overflow-y: auto;
      &.tabContent {
        max-height: calc(100vh - 270px);
      }
    }
    .right {
      flex: 1;
      max-height: calc(100vh - 158px);
      overflow-y: auto;
      &.tabContent {
        max-height: calc(100vh - 270x);
      }
    }
  }
  .sub-model__main {
    width: 100%;
    ul,
    li {
      list-style: none;
      padding-left: 10px;
      width: 100%;
    }
    .row-even {
      background: #e9e6e6;
    }
    .row-odd {
      background: #fff;
    }
    &.padding50 {
      padding-left: 100px;
    }
    .field-list__item {
      // display: flex;
      .field-row {
        padding: 5px 0 5px 10px;
      }
      .field-name {
        color: #409eff;
        width: 150px;
      }
      span {
        width: 150px;
        display: inline-block;
        margin-right: 10px;
        font-size: 12px;
        white-space: break-spaces;
        word-wrap: break-word;
        height: auto;
      }
    }
    .title {
      font-size: 18px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      &::before {
        content: '';
        display: inline-block;
        width: 3px;
        height: 16px;
        margin-right: 5px;
        background-color: #409eff;
        vertical-align: middle;
        margin-top: -3px;
      }
    }
  }
  // .ellipsis-text {
  //   white-space: nowrap; /* 不换行 */
  //   overflow: hidden; /* 隐藏溢出内容 */
  //   text-overflow: ellipsis; /* 显示省略号 */
  //   max-width: 600px; /* 设置最大宽度 */
  // }
  // .adaptive-column .el-descriptions__item {
  //   flex: 1; /* 让每个 item 自适应宽度 */
  // }
}
</style>
